package mysql

import (
	"fmt"
	"gitee.com/captials-team/ubdframe/src/common/utils"
	"gitee.com/captials-team/ubdframe/src/domain/configstc"
	"gitee.com/captials-team/ubdframe/src/domain/dto"
	"gitee.com/captials-team/ubdframe/src/domain/dto/paginate"
	"gitee.com/captials-team/ubdframe/src/domain/interfaces"
	"gitee.com/captials-team/ubdframe/src/domain/models"
	mysqlClients "gitee.com/captials-team/ubdframe/src/infrastructure/clients/mysql"
	"gorm.io/gorm"
)

func NewAdminLogDao(conf configstc.DBConfig) *AdminLogDao {
	return &AdminLogDao{
		db:   mysqlClients.NewGormDB(conf),
		conf: conf,
	}
}

type AdminLogDao struct {
	db   *gorm.DB
	conf configstc.DBConfig
}

func (dao *AdminLogDao) Search(search *dto.SearchAdminLogParams, pa *paginate.Pager) ([]*models.AdminLog, *paginate.Pager, error) {
	if search == nil {
		search = &dto.SearchAdminLogParams{}
	}
	if pa == nil {
		pa = &paginate.Pager{}
	}
	pa.Correct()

	db := dao.db.Model(new(models.AdminLog))

	var list []*models.AdminLog

	if search.Keywords != "" {
		keywords := search.Keywords + "%"
		db = db.Where("(nickname like ? OR account like ? OR ip like ?)", keywords, keywords, keywords)
	}
	if search.Uid > 0 {
		db = db.Where("admin_id=?", search.Uid)
	}
	if search.Username != "" {
		db = db.Where("account=?", search.Username)
	}

	if ret := db.Count(&pa.Total); ret.Error != nil {
		return list, pa, ret.Error
	}

	db = db.Order("id desc")
	if ret := db.Limit(pa.Size).Offset(pa.Offset()).Find(&list); ret.Error != nil {
		return list, pa, ret.Error
	}
	pa.Correct()
	return list, pa, nil
}

func (dao *AdminLogDao) Add(add *models.AdminLog) (int64, error) {
	if add.Id > 0 {
		return 0, fmt.Errorf("not support update")
	}
	add.Device = add.Device[:utils.Min(100, len(add.Device))] //device不超过100长度
	ret := dao.db.Model(add).Create(add)
	if ret.Error != nil {
		return 0, ret.Error
	}
	if ret.RowsAffected == 0 {
		return 0, fmt.Errorf("add fail")
	}

	return add.Id, nil
}

func (dao *AdminLogDao) Migrate() (int64, error) {
	return 1, dao.db.AutoMigrate(new(models.AdminLog))
}

func (dao *AdminLogDao) DB() *gorm.DB {
	return dao.db
}

func (dao *AdminLogDao) Use(db *gorm.DB) interfaces.ItfAdminLog {
	return &AdminLogDao{db: db}
}
